/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.commons.speeder.limiter;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ArrayBlockingQueue;

/**
 *
 * @author zwlin
 */
public class SpeedLimitTokenBucket implements SpeedLimiter {

//	private int countPerTime;
	private int intevalSecond;
	private final ArrayBlockingQueue<Object> queue;
	private final ArrayList< Object> objs;

	private boolean isAlive;
	private final Timer generateTimer;
//	private final int max;

	public boolean TryGetToken() {
		if (!isAlive) {
			return false;
		}
		try {
			return queue.remove() != null;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean GetToken() {
		if (!isAlive) {
			return false;
		}
		try {
			return queue.take() != null;
		} catch (Exception e) {
			return false;
		}
	}

	public boolean alive() {
		return isAlive;
	}

	public SpeedLimitTokenBucket(int countPerTime, int intevalSecond, int max) {
//		this.countPerTime = countPerTime;
		this.intevalSecond = intevalSecond;
//		this.max = max;
		this.queue = new ArrayBlockingQueue<>(max);

		this.isAlive = false;
		this.generateTimer = new Timer("TokenBucketGenerateTimer");

		Object obj = new Object();
		this.objs = new ArrayList<>(countPerTime);
		for (int i = 0; i < countPerTime; ++i) {
			this.objs.add(obj);
		}
	}

	public void start() {
		this.isAlive = true;
		generateTimer.scheduleAtFixedRate(new TokenGenerateTask(), 0, intevalSecond * 1000);
	}

	public void stop() {
		this.isAlive = false;
		generateTimer.cancel();
	}

    @Override
    public boolean tryGetThrough(String key) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void waitGetThrough(String key) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public boolean isActivated() {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private class TokenGenerateTask extends TimerTask {

		@Override
		public void run() {
			try {
				queue.addAll(objs);
			} catch (Exception e) {
			}
		}
	}
}
